import express from 'express';
import { FileStorage } from '../FileStorage';
import type { Diary } from '../FileStorage';

const router = express.Router();

// 获取所有日记
router.get('/diarys', async (req, res) => {
  try {
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const diarys = await fileStorage.getEntities<Diary>('diarys');
    res.json({
      code: 200,
      data: diarys,
      message: 'success'
    });
  } catch (error) {
    console.error('获取日记列表失败:', error);
    res.status(500).json({
      code: 500,
      error: '获取日记列表失败'
    });
  }
});

// 根据ID获取日记
router.get('/diarys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const diary = await fileStorage.findEntityById<Diary>('diarys', id);
    
    if (!diary) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的日记'
      });
    }
    
    res.json({
      code: 200,
      data: diary,
      message: 'success'
    });
  } catch (error) {
    console.error('获取日记失败:', error);
    res.status(500).json({
      code: 500,
      error: '获取日记失败'
    });
  }
});

// 创建新日记
router.post('/diarys', async (req, res) => {
  try {
    const diaryData: Diary = req.body;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const newDiary = await fileStorage.addEntity<Diary>('diarys', diaryData);
    
    res.status(201).json({
      code: 201,
      data: newDiary,
      message: '日记创建成功'
    });
  } catch (error) {
    console.error('创建日记失败:', error);
    res.status(500).json({
      code: 500,
      error: '创建日记失败'
    });
  }
});

// 更新日记
router.put('/diarys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const updateData: Partial<Diary> = req.body;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const updatedDiary = await fileStorage.updateEntity<Diary>('diarys', id, updateData);
    
    if (!updatedDiary) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的日记'
      });
    }
    
    res.json({
      code: 200,
      data: updatedDiary,
      message: '日记更新成功'
    });
  } catch (error) {
    console.error('更新日记失败:', error);
    res.status(500).json({
      code: 500,
      error: '更新日记失败'
    });
  }
});

// 删除日记
router.delete('/diarys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const result = await fileStorage.deleteEntity('diarys', id);
    
    if (!result) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的日记'
      });
    }
    
    res.json({
      code: 200,
      message: '日记删除成功'
    });
  } catch (error) {
    console.error('删除日记失败:', error);
    res.status(500).json({
      code: 500,
      error: '删除日记失败'
    });
  }
});

export default router;